import request from '@/http';
import { 
  ApiResponse, 
  UserProfile, 
  AvatarUploadResponse, 
  RegisterRequest, 
  LoginRequest, 
  LoginResponse,
  InvitationCode,
  CreateInvitationCodeRequest,
  CreateInvitationCodeResponse,
  Team,
  TeamMember,
  CreateTeamRequest,
  UpdateTeamRequest,
  JoinTeamRequest
} from '../types/account';
import { PaginatedResponse } from '../types/common';
import { useAuthStore } from '../store/useAuthStore';

enum Url {
  login = '/api/account/api-token-auth/',
  register = '/api/account/register/',
  uploadAvatar = '/api/account/avatar/',
  profile = '/api/account/profile/',
  invitationCode = '/api/account/invitation_code/',
  teams = '/api/account/teams/',
}


export const accountService = {
  // 用户注册
  async register(data: RegisterRequest): Promise<ApiResponse<RegisterRequest>> {
    const response = await request.post(Url.register, data);
    return response.data;
  },

   // 用户登录
  async login(data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
    const response = await request.post<LoginResponse>(Url.login, data);
    if (response.data.data.token && response.data.data.user) {
      useAuthStore.getState().setAuth(response.data.data.token, response.data.data.user);
    }
    return response.data;
  },

  // 上传头像
  async uploadAvatar(formData: FormData): Promise<ApiResponse<AvatarUploadResponse>> {
    const response = await request.post(Url.uploadAvatar, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  },

  // 获取用户资料
  async getProfile(): Promise<ApiResponse<UserProfile>> {
    const response = await request.get(Url.profile);
    return response.data;
  },

  // 创建用户资料（首次登录时使用）
  async createProfile(data: Partial<UserProfile>): Promise<ApiResponse<UserProfile>> {
    const response = await request.post(Url.profile, data);
    return response.data;
  },

  // 更新用户资料
  async updateProfile(data: UserProfile): Promise<ApiResponse<UserProfile>> {
    const response = await request.put(Url.profile, data);
    return response.data;
  },

  // 获取头像完整URL
  getAvatarUrl(avatar: string): string {
    return request.getAvatarUrl(avatar);
  },

  // 获取当前用户的头像URL
  async getCurrentUserAvatar(): Promise<string> {
    try {
      const response = await this.getProfile();
      if (response.data && response.data.avatar) {
        console.log(response.data.avatar);
        return this.getAvatarUrl(response.data.avatar);
      }
      return '';
    } catch (error) {
      console.error('获取用户头像失败:', error);
      return '';
    }
  },

  // 登出
  logout() {
    useAuthStore.getState().clearAuth();
  },

  // 检查是否已登录
  isAuthenticated(): boolean {
    return !!useAuthStore.getState().token;
  },

  // ================== 邀请码管理相关API ==================

  // 获取邀请码列表
  async getInvitationCodes(page?: number): Promise<ApiResponse<PaginatedResponse<InvitationCode>>> {
    const params = page ? { page } : {};
    const response = await request.get(Url.invitationCode, { params });
    return response.data;
  },

  // 生成邀请码
  async createInvitationCodes(data: CreateInvitationCodeRequest): Promise<ApiResponse<InvitationCode[]>> {
    const response = await request.post(Url.invitationCode, data);
    return response.data;
  },

  // 删除邀请码
  async deleteInvitationCode(codeId: number): Promise<ApiResponse<null>> {
    const response = await request.delete(`${Url.invitationCode}${codeId}/`);
    return response.data;
  },

  // 导出邀请码到Excel
  async exportInvitationCodes(): Promise<Blob> {
    const response = await request.get(`${Url.invitationCode}export/`, {
      responseType: 'blob',
    });
    return response.data as any;
  },

  // ================== 团队管理相关API ==================

  // 获取团队列表
  async getTeams(): Promise<ApiResponse<PaginatedResponse<Team>>> {
    const response = await request.get(Url.teams);
    return response.data;
  },

  // 获取团队详情
  async getTeam(teamId: number): Promise<ApiResponse<Team>> {
    const response = await request.get(`${Url.teams}${teamId}/`);
    return response.data;
  },

  // 创建团队
  async createTeam(data: CreateTeamRequest): Promise<ApiResponse<Team>> {
    const response = await request.post(Url.teams, data);
    return response.data;
  },

  // 更新团队信息
  async updateTeam(teamId: number, data: UpdateTeamRequest): Promise<ApiResponse<Team>> {
    const response = await request.put(`${Url.teams}${teamId}/`, data);
    return response.data;
  },

  // 删除团队
  async deleteTeam(teamId: number): Promise<ApiResponse<null>> {
    const response = await request.delete(`${Url.teams}${teamId}/`);
    return response.data;
  },

  // 加入团队
  async joinTeam(teamId: number, data: JoinTeamRequest): Promise<ApiResponse<null>> {
    const requestData = {
      ...data,
      team_id: teamId,
    };
    const response = await request.post(`${Url.teams}${teamId}/join/`, requestData);
    return response.data;
  },

  // 获取团队成员列表
  async getTeamMembers(teamId: number): Promise<ApiResponse<TeamMember[]>> {
    const response = await request.get(`${Url.teams}${teamId}/members/`);
    return response.data;
  },

  // 获取用户所属的团队
  async getMyTeam(): Promise<ApiResponse<Team[]>> {
    const response = await request.get(`${Url.teams}my_team/`);
    return response.data;
  },

  // 退出团队
  async leaveTeam(teamId: number): Promise<ApiResponse<null>> {
    const response = await request.post(`${Url.teams}${teamId}/leave/`);
    return response.data;
  },
}; 